import React from "react";
import { IPSetRule } from "../../api/types";
import styles from "./RuleModal.module.css";

interface AddOptions {
  type: "add";
}

interface EditOptions {
  type: "edit";
  rule: IPSetRule;
}

type Options = AddOptions | EditOptions;

interface RuleModalRef {
  add: (data: Omit<AddOptions, "type">) => void;
  edit: (data: Omit<EditOptions, "type">) => void;
}

interface RuleModalProps {
  currentNetworkIP?: string;
  defaultTimeout?: number;
  supportedRemarks?: boolean;
  onSave?: (data: {
    type: "add" | "edit";
    rule: IPSetRule;
  }) => Promise<boolean>;
}

const RuleModalComponent = React.forwardRef<RuleModalRef, RuleModalProps>(
  ({ currentNetworkIP, defaultTimeout, supportedRemarks, onSave }, ref) => {
    const [options, setOptions] = React.useState<Options>();
    const [ip, setIP] = React.useState("");
    const [timeout, setTimeout] = React.useState(0);
    const [remarks, setRemarks] = React.useState("");

    const handleAdd = React.useCallback(
      (data: Omit<AddOptions, "type">) => {
        setIP("");
        setTimeout(defaultTimeout || 0);
        setRemarks("");
        setOptions({
          ...data,
          type: "add",
        });
      },
      [defaultTimeout]
    );

    const handleEdit = React.useCallback((data: Omit<EditOptions, "type">) => {
      setIP(data.rule.ip);
      setTimeout(data.rule.timeout);
      setRemarks(data.rule.remarks);
      setOptions({
        ...data,
        type: "edit",
      });
    }, []);

    const onClickCurrentNetwork = React.useCallback(() => {
      setIP(currentNetworkIP || "");
    }, [currentNetworkIP]);

    const onClickCancel = React.useCallback(() => {
      setOptions(undefined);
    }, []);

    const onClickSave = React.useCallback(async () => {
      if (!options?.type) {
        return;
      }
      const rule: IPSetRule = {
        ip: options.type === "edit" ? options.rule.ip : ip,
        timeout: timeout,
        remarks: remarks,
      };
      const flag = await onSave?.({ type: options.type, rule: rule });
      if (flag) {
        setOptions(undefined);
      }
    }, [ip, onSave, options, remarks, timeout]);

    React.useImperativeHandle(
      ref,
      () => ({
        add: handleAdd,
        edit: handleEdit,
      }),
      [handleAdd, handleEdit]
    );

    if (!options) {
      return null;
    }

    return (
      <div className={styles.modal}>
        <div className={styles.modalContent}>
          <div className={styles.header}>
            {options.type === "add" ? "添加规则" : "编辑规则"}
          </div>
          <div className={styles.row}>
            <div className={styles.label}>IP: </div>
            <input
              type="text"
              placeholder="请输入IP"
              value={ip}
              onChange={(e) => setIP(e.currentTarget.value)}
            />
            {currentNetworkIP ? (
              <button onClick={onClickCurrentNetwork}>当前网络</button>
            ) : null}
          </div>
          {defaultTimeout && defaultTimeout > 0 ? (
            <div className={styles.row}>
              <div className={styles.label}>有效时长(秒): </div>
              <input
                type="number"
                placeholder="请输入有效时长"
                value={timeout}
                onChange={(e) => {
                  setTimeout(Number(e.currentTarget.value));
                }}
              />
              <button onClick={() => setTimeout(3600 * 12)}>12h</button>
              <button onClick={() => setTimeout(86400 * 1)}>1d</button>
              <button onClick={() => setTimeout(86400 * 2)}>2d</button>
              <button onClick={() => setTimeout(86400 * 3)}>3d</button>
              <button onClick={() => setTimeout(86400 * 7)}>7d</button>
            </div>
          ) : null}
          {!!supportedRemarks ? (
            <div className={styles.row}>
              <div className={styles.label}>备注: </div>
              <input
                type="text"
                placeholder="请输入备注"
                value={remarks}
                onChange={(e) => setRemarks(e.currentTarget.value)}
              />
            </div>
          ) : null}

          <div className={styles.bottom}>
            <button onClick={onClickCancel}>取消</button>
            <button onClick={onClickSave}>保存</button>
          </div>
        </div>
      </div>
    );
  }
);

type RuleModal = RuleModalRef;

const RuleModal = React.memo(RuleModalComponent);

RuleModal.displayName = "RuleModal";

export default RuleModal;
